"""
Chrome浏览器路径查找器
"""
import os
import winreg
from pathlib import Path
from typing import Optional, List
from core.utils.logger_manager import LoggerManager


class ChromeFinder:
    """Chrome浏览器路径查找器"""
    
    def __init__(self):
        self.logger = LoggerManager.get_logger("chrome_finder")
    
    def find_chrome_path(self) -> Optional[str]:
        """查找Chrome浏览器路径"""
        # 常见的Chrome安装路径
        common_paths = [
            r"C:\Program Files\Google\Chrome\Application\chrome.exe",
            r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",
            os.path.expanduser(r"~\AppData\Local\Google\Chrome\Application\chrome.exe"),
            r"C:\Users\%USERNAME%\AppData\Local\Google\Chrome\Application\chrome.exe"
        ]
        
        # 检查常见路径
        for path in common_paths:
            expanded_path = os.path.expandvars(path)
            if os.path.exists(expanded_path):
                self.logger.info(f"找到Chrome路径: {expanded_path}")
                return expanded_path
        
        # 从注册表查找
        registry_path = self._find_chrome_in_registry()
        if registry_path and os.path.exists(registry_path):
            self.logger.info(f"从注册表找到Chrome路径: {registry_path}")
            return registry_path
        
        # 搜索系统PATH
        path_result = self._find_chrome_in_path()
        if path_result:
            self.logger.info(f"从PATH找到Chrome路径: {path_result}")
            return path_result
        
        self.logger.error("未找到Chrome浏览器")
        return None
    
    def _find_chrome_in_registry(self) -> Optional[str]:
        """从注册表查找Chrome路径"""
        try:
            # 查找Chrome的注册表项
            registry_keys = [
                (winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe"),
                (winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe"),
                (winreg.HKEY_CURRENT_USER, r"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe"),
            ]
            
            for hkey, subkey in registry_keys:
                try:
                    with winreg.OpenKey(hkey, subkey) as key:
                        path, _ = winreg.QueryValueEx(key, "")
                        if path and os.path.exists(path):
                            return path
                except (FileNotFoundError, OSError):
                    continue
            
            # 查找Google Chrome的安装信息
            chrome_keys = [
                (winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Google\Chrome"),
                (winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\WOW6432Node\Google\Chrome"),
                (winreg.HKEY_CURRENT_USER, r"SOFTWARE\Google\Chrome"),
            ]
            
            for hkey, subkey in chrome_keys:
                try:
                    with winreg.OpenKey(hkey, subkey) as key:
                        install_path, _ = winreg.QueryValueEx(key, "InstallPath")
                        chrome_exe = os.path.join(install_path, "chrome.exe")
                        if os.path.exists(chrome_exe):
                            return chrome_exe
                except (FileNotFoundError, OSError):
                    continue
            
        except Exception as e:
            self.logger.warning(f"注册表查找失败: {str(e)}")
        
        return None
    
    def _find_chrome_in_path(self) -> Optional[str]:
        """从系统PATH中查找Chrome"""
        try:
            import shutil
            chrome_path = shutil.which("chrome")
            if chrome_path:
                return chrome_path
            
            # 尝试其他可能的命令名
            for cmd in ["google-chrome", "chromium", "chromium-browser"]:
                path = shutil.which(cmd)
                if path:
                    return path
                    
        except Exception as e:
            self.logger.warning(f"PATH查找失败: {str(e)}")
        
        return None
    
    def get_chrome_version(self, chrome_path: str) -> Optional[str]:
        """获取Chrome版本信息"""
        try:
            import subprocess
            result = subprocess.run(
                [chrome_path, "--version"],
                capture_output=True,
                text=True,
                timeout=10
            )
            
            if result.returncode == 0:
                version = result.stdout.strip()
                self.logger.info(f"Chrome版本: {version}")
                return version
            else:
                self.logger.warning(f"获取Chrome版本失败: {result.stderr}")
                
        except Exception as e:
            self.logger.warning(f"获取Chrome版本异常: {str(e)}")
        
        return None
    
    def is_chrome_running(self) -> bool:
        """检查Chrome是否正在运行"""
        try:
            import psutil
            for proc in psutil.process_iter(['pid', 'name']):
                if proc.info['name'] and 'chrome' in proc.info['name'].lower():
                    return True
        except Exception as e:
            self.logger.warning(f"检查Chrome运行状态失败: {str(e)}")
        
        return False
    
    def kill_chrome_processes(self) -> bool:
        """终止所有Chrome进程"""
        try:
            import psutil
            killed_count = 0
            
            for proc in psutil.process_iter(['pid', 'name']):
                if proc.info['name'] and 'chrome' in proc.info['name'].lower():
                    try:
                        proc.kill()
                        killed_count += 1
                    except (psutil.NoSuchProcess, psutil.AccessDenied):
                        continue
            
            if killed_count > 0:
                self.logger.info(f"已终止{killed_count}个Chrome进程")
                return True
            else:
                self.logger.info("没有找到Chrome进程")
                return True
                
        except Exception as e:
            self.logger.error(f"终止Chrome进程失败: {str(e)}")
            return False
